package cn.rkylin.oms.common.utils;

import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.SecretException;
import com.taobao.api.security.SecurityClient;
import org.apache.commons.lang.StringUtils;

/**
 * 淘宝加密类
 * @author liming
 * @date 2017-12-19
 */
public class TaobaoEncrypt {

    /**
     * securityClient
     */
    private SecurityClient securityClient = null;

    /**
     * sessionKey
     */
    private String sessionKey = "";

    /**
     * appKey
     */
    private String appKey="";

    /**
     * appSecret
     */
    private String appSecret="";

    /**
     * apiUrl
     */
    private String apiUrl="";

    /**
     * 构造方法
     * @param appKey
     * @param appSecret
     * @param sessionKey
     * @param apiUrl
     */
    public TaobaoEncrypt(String appKey, String appSecret, String sessionKey,String apiUrl) {
        this.appKey = appKey;
        this.appSecret = appSecret;
        this.sessionKey = sessionKey;
        this.apiUrl= apiUrl;
        if (securityClient == null) {
            securityClient = new SecurityClient(new DefaultTaobaoClient(apiUrl, appKey, appSecret),
                    "HVkLUFP49UaCMJWhbvxqgZpUhBU3h4rBAnLGtqCHaXA=");
        }
    }
    /**
     * 淘宝加密字段的解密
     *
     * @param field
     * @param type
     * @return
     */
    public String decript(String field, String type) {
        String returnValue = field;
        if (StringUtils.isNotBlank(field)) {
            try {
                if (SecurityClient.isEncryptData(returnValue, type)) {
                    returnValue = securityClient.decrypt(field, type, sessionKey);
                }
            } catch (SecretException e) {
                e.printStackTrace();
            }
        }
        return returnValue;
    }


    /**
     * 淘宝加密字段的加密
     *
     * @param field
     * @param type
     * @return
     */
    public String encrypt(String field, String type) {
        String returnValue = field;
        if (StringUtils.isNotBlank(field)) {
            try {
                returnValue = securityClient.encrypt(field, type, sessionKey);
            } catch (SecretException e) {
                e.printStackTrace();
            }
        }
        return returnValue;
    }
}
